package com.npjscg.medicalpro.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.npjscg.medicalpro.common.Constants;
import com.npjscg.medicalpro.common.ValidationEnum;
import com.npjscg.medicalpro.controller.dto.UserDTO;
import com.npjscg.medicalpro.controller.dto.UserPasswordDTO;
import com.npjscg.medicalpro.entity.User;
import com.npjscg.medicalpro.entity.Validation;
import com.npjscg.medicalpro.exception.ServiceException;
import com.npjscg.medicalpro.mapper.UserMapper;
import com.npjscg.medicalpro.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.npjscg.medicalpro.service.IValidationService;
import com.npjscg.medicalpro.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author raote
 * @since 2022-06-23
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private IValidationService validationService;

    @Resource
    private UserMapper userMapper;

    @Override
    public UserDTO login(UserDTO userDTO) {
        User one = getUserInfo(userDTO);
        if (one != null) {
            userDTO.setId(one.getId());
            userDTO.setNickname(one.getNickname());
            userDTO.setToken(TokenUtils.genToken(userDTO.getId(),userDTO.getPassword()));
            userDTO.setAvatar(one.getAvatar());
            return userDTO;
        } else {
            throw new ServiceException(Constants.CODE_600, "用户名或密码错误，请选择正确登录身份");
        }
    }

    @Override
    public void changePassword(UserPasswordDTO userPasswordDTO) {
        int update = userMapper.updatePassword(userPasswordDTO);
        if (update < 1) {
            throw new ServiceException(Constants.CODE_600, "密码错误");
        }

    }

    @Override
    public User register(UserDTO userDTO) {
        // 用户密码 md5加密
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email", userDTO.getEmail());
        if (getOne(queryWrapper) != null) {
            throw new ServiceException("-1", "邮箱已被注册！请勿重复使用");
        }
        userDTO.setPassword(SecureUtil.md5(userDTO.getPassword()));
        User one = getUserInfo(userDTO);
        if (one == null) {
            one = new User();
            BeanUtil.copyProperties(userDTO, one, true);

            if (one.getNickname() == null) {
                one.setNickname(one.getUsername());
            }
            save(one);  // 把 copy完之后的用户对象存储到数据库
        } else {
            throw new ServiceException(Constants.CODE_600, "用户已存在");
        }
        return one;
    }

    @Override
    public IPage selectPage(Page<User> page, String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role",0);
        queryWrapper.like("username",username);
        return userMapper.selectPage(page,queryWrapper);
    }

    @Override
    public void edit(UserDTO userDTO) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email", userDTO.getEmail());
        if (!StrUtil.isBlank(userDTO.getEmail())){
            if (getOne(queryWrapper) != null) {
                throw new ServiceException("-1", "邮箱已被注册！请勿重复使用");
            }
        }
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", userDTO.getId());
        if (!StrUtil.isBlank(userDTO.getUsername()))
            updateWrapper.set("username", userDTO.getUsername());
        if (!StrUtil.isBlank(userDTO.getPassword()))
            updateWrapper.set("password", SecureUtil.md5(userDTO.getPassword()));
        if (!StrUtil.isBlank(userDTO.getNickname()))
            updateWrapper.set("nickname",userDTO.getNickname());
        if (!StrUtil.isBlank(userDTO.getMedicalorg()))
            updateWrapper.set("medicalorg", userDTO.getMedicalorg());
        if (!StrUtil.isBlank(userDTO.getEmail()))
            updateWrapper.set("email",userDTO.getEmail());
        try {
            boolean update = update(updateWrapper);
            System.out.println(update);
        } catch (Exception e) {
            throw e;
        }
    }

    @Override
    public void sendEmailCode(String email, Integer type) throws MessagingException{
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email",email);

        if (count(queryWrapper) == 0)
            throw new ServiceException("-1","该邮箱未注册用户！");

        Date now = new Date();
        // 先查询同类型code
        QueryWrapper<Validation> validationQueryWrapper = new QueryWrapper<>();
        validationQueryWrapper.eq("email", email);
        validationQueryWrapper.eq("type", type);
        validationQueryWrapper.ge("time", now);  // 查询数据库没过期的code
        Validation validation = validationService.getOne(validationQueryWrapper);
        if (validation != null) {
            throw new ServiceException("-1", "当前您的验证码仍然有效，请不要重复发送");
        }


        String code = RandomUtil.randomNumbers(4); // 随机一个 4位长度的验证码

        if (ValidationEnum.LOGIN.getCode().equals(type)) {
            SimpleMailMessage message=new SimpleMailMessage();
            message.setFrom(from);  // 发送人
            message.setTo(email);
            message.setSentDate(now);
            message.setSubject("【MedicalPro】登录邮箱验证");
            message.setText("您本次登录的验证码是：" + code + "，有效期5分钟。请妥善保管，切勿泄露");
            javaMailSender.send(message);
        } else if (ValidationEnum.FORGET_PASS.getCode().equals(type)){
            MimeMessage message = javaMailSender.createMimeMessage();
            MimeMessageHelper helper=new MimeMessageHelper(message);
            helper.setSubject("【MedicalPro】忘记密码验证");
            helper.setFrom(from);  // 发送人
            helper.setTo(email);
            helper.setSentDate(now);  // 富文本
            String context="<b>尊敬的用户：</b><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;您好，您本次忘记密码的验证码是："+
                    "<b color=\"'red'\">"  + code + "</b><br>"
                    +"，有效期5分钟。请妥善保管，切勿泄露";
            helper.setText(context, true);
            javaMailSender.send(message);
        }


        // 发送成功之后，把验证码存到数据库
        validationService.saveCode(email, code, type, DateUtil.offsetMinute(now, 5));


    }

    @Override
    public UserDTO loginEmail(UserDTO userDTO) {
        String email = userDTO.getEmail();
        String code = userDTO.getCode();
        int role = userDTO.getRole();




        // 先查询 邮箱验证的表，看看之前有没有发送过  邮箱code，如果不存在，就重新获取
        QueryWrapper<Validation> validationQueryWrapper = new QueryWrapper<>();
        validationQueryWrapper.eq("email", email);
        validationQueryWrapper.eq("code", code);
        Validation v = validationService.getOne(validationQueryWrapper);
        if (v == null)
            throw new ServiceException("-1", "邮箱或验证码错误！");
        else {
            validationQueryWrapper.ge("time", new Date());  // 查询数据库没过期的code, where time >= new Date()
            Validation one = validationService.getOne(validationQueryWrapper);
            if (one == null) {
                throw new ServiceException("-1", "验证码过期，请重新获取");
            }
        }


        // 如果验证通过了，就查询要不过户的信息
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("email", email);  //存根据email查询用户信息
        User user = getOne(userQueryWrapper);


        if (user == null) {
            throw new ServiceException("-1", "未找到用户,请确认绑定邮箱");
        }

        if (user.getRole() != role) {
            throw new ServiceException("-1", "未找到用户，请选择正确身份");
        }

        BeanUtil.copyProperties(user, userDTO, true);
        // 设置token
        String token = TokenUtils.genToken(user.getId(), user.getPassword());//得到的是储存在数据库中的加密后的密码
        userDTO.setToken(token);


        return userDTO;
    }


    //根据用户名密码,role查询
    private User getUserInfo(UserDTO userDTO) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", userDTO.getUsername());
        queryWrapper.eq("password", userDTO.getPassword());
        queryWrapper.eq("role", userDTO.getRole());
        User one;
        try {
            one = getOne(queryWrapper); // 从数据库查询用户信息
        } catch (Exception e) {
            throw e;
        }
        return one;
    }
}
